<template>
  <div class="material-manage">
    <a-table
      bordered
      v-if="inRender"
      :expandIcon="expandIcon"
      :columns="columns"
      :rowKey="record => record.id"
      :data-source="materialTree"
      :default-expand-all-rows="true"
      :pagination="false">
      <template slot="action" slot-scope="text, record">
        <div v-if="record.uplodable && customHandle.materialDirectory && customHandle.materialDirectory.length">
          <span v-for="auth in customHandle.materialDirectory" :key="Math.random()">
            <a-icon
              :type="auth.icon"
              :title="auth.name"
              :style="{ color: auth.color }"
              class="m-r-sm cursor-pointer"
              @click="handleClick(auth, record)">
            </a-icon>
          </span>
        </div>
        <div v-if="record.type === 'file' && customHandle.materialFile && customHandle.materialFile.length">
          <span v-for="auth in customHandle.materialFile" :key="Math.random()">
            <a-icon
              :type="auth.icon"
              :title="auth.name"
              :style="{ color: auth.color }"
              class="m-r-sm cursor-pointer"
              @click="handleClick(auth, record)">
            </a-icon>
          </span>
        </div>
        <div v-if="record.refId">
          <a-icon type="cloud-download" title="打包下载" class="m-r-sm cursor-pointer" @click="downPackage(record)"/>
        </div>
      </template>

      <template slot="name" slot-scope="text, record">
        <a-icon
          v-if="record.uplodable"
          class="m-r-sm text-yellow"
          :type="record.showOpenFolder?'folder-open':'folder'"/>
        <span @click="previewNode(record)" @dblclick="previewNode(record)"
              :title="record.name">{{ record.nick || record.name }}</span>
      </template>

    </a-table>
  </div>

</template>

<script>
import materialApi from '@/api/material'
import AButton from 'ant-design-vue/es/button/button'
import moment from 'moment'

const columns = [
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
    ellipsis: true,
    scopedSlots: { customRender: 'name' }
  },
  {
    title: '上传时间',
    dataIndex: 'uploadTime',
    key: 'uploadTime',
    width: '18%',
    align: 'center',
    customRender: (text, row, index) => {
      return row.uploadTime ? moment(row.uploadTime).format('YYYY-MM-DD HH:mm:ss') : ''
    }
  },
  {
    title: '大小',
    dataIndex: 'fileSize',
    key: 'fileSize',
    width: '10%',
    align: 'center'
  },
  {
    title: '操作',
    key: 'action',
    width: '20%',
    scopedSlots: { customRender: 'action' },
    align: 'center'
  }
]

const customHandle = {
  materialDirectory: [
    {
      name: '上传',
      icon: 'upload',
      cb: 'upload'
    }
  ],
  materialFile: [
    {
      name: '浏览',
      icon: 'eye',
      cb: 'preView',
      color: '#3387EA'
    },
    {
      name: '下载',
      icon: 'download',
      cb: 'download',
      color: '#6DD400'
    },
    {
      name: '删除',
      icon: 'delete',
      cb: 'remove',
      color: 'red'
    }
  ]
}

export default {
  name: 'ProjectReplaceMaterials',
  data() {
    return {
      columns,
      inRender: false,
      materialTree: [],
      showOpenFolder: false,
      customHandle: {}
    }
  },
  props: {
    projectId:{
      type: Number
    }
  },
  components: {
    AButton
  },
  created() {
  },
  mounted() {
    this.getProjectInfo()
    const _this = this
    this.Event.$on('_REFRESH_MATERIAL_MANAGER_', data => {
      if (data.projectId === _this.projectId) {
        _this.getProjectResourceList()
      }
    })
  },
  methods: {
    async getProjectInfo() {
      this.getProjectResourceList()
    },
    getProjectResourceList() {
      const params = {
        projectId: this.projectId,
        listType: 0
      }
      materialApi.getMaterialList(params).then(d => {
        const list = Array.from(d).map(item => {
          return item.categoryInstDTO
        })
        this.formatData(list)
        this.projectResourceList = list
        this.materialTree = this.projectResourceList
        this.initMaterialAuth()
      })
    },
    formatData(list, privilege) {
      list.forEach(item => {
        if (!item.privilege && privilege) {
          item.privilege = privilege
        }
        if (item.files && item.files.length > 0) {
          const files = this._.cloneDeep(item.files).map(file => {
            file.privilege = item.privilege
            return file
          })
          if (item.children) {
            item.children = item.children.concat(files)
          } else {
            item.children = files
          }
        }
        if (item.children) {
          this.formatData(item.children, item.privilege)
        }
      })
    },
    download(file) {
      const params = {
        materialFileId: file.id,
        fileName: file.name,
        mimetype: 'download'
      }
      materialApi.downloadMaterial(params)
    },
    downPackage(record) {
      const params = {
        projectId: this.projectId,
        categoryInstIds: record.id// 不传，下载整个项目材料
      }
      materialApi.downPackage(params)
    },
    preView(file) {
      this.$emit('addTab', {type: 'file', file: file})
    },
    ReplaceMaterials(record,type) {
      let owner = this
      owner.$dialog({
        title: '替换结果文件',
        content: () => import('@v/investmentOnline/interfaceMonitor/dialog/ReplaceMaterialsDialog'),
        width: 500,
        scrollable:true,
        bodyStyle: {
          height: type === 'delete'?'350px':'400px',
          overflow: 'hidden',
          padding: '0px'
        },
        centered: true,
        maskClosable: false,
        props: {
          projectId: this.projectId,
          directoryInstId:type === 'delete'?record.materialDirectoryInstId:record.id,
          materialFileId:record.id,
          type:type
        },
        on: {
          ok (ctl) {
            const dialogCtl = ctl.getDialogCtl()
            dialogCtl.replaceMaterials().then(res => {
              if (res.code === 200 || (res.length > 0 && res[0])) {
                owner.$message.success('操作成功')
                owner.Event.$emit('_REFRESH_MATERIAL_MANAGER_', {projectId: owner.projectId})
                ctl.closeDialog()
              } else {
                owner.$message.error('操作失败！')
              }
            })
          },
          cancel() {
          }
        }
      });
    },
    uploadSuccess(data) {
      this.getProjectResourceList()
      this.Event.$emit('_REFRESH_MATERIAL_MANAGER_', {projectId: this.projectId})
    },
    expandIcon(props) {
      if (props.record.type !== 'file') {
        if (props.expanded) {
          props.record.showOpenFolder = true
          return <a-icon type="down" class="m-r-sm" style="color:#9C9C9C;" onClick={e => {
            props.record.showOpenFolder = !props.record.showOpenFolder
            props.onExpand(props.record, e)
          }}/>
        } else {
          props.record.showOpenFolder = false
          return <a-icon type="right" class="m-r-sm" style="color:#9C9C9C;" onClick={e => {
            props.record.showOpenFolder = !props.record.showOpenFolder
            props.onExpand(props.record, e)
          }}/>
        }
      } else {
        return <span class="m-r-sm"></span>
      }
    },
    initMaterialAuth() {
      this.customHandle = customHandle
    },
    handleClick(item, record) {
      switch (item.name) {
        case '上传': {
          this.ReplaceMaterials(record,'upload')
          break
        }
        case '下载': {
          this.download(record)
          break
        }
        case '浏览': {
          this.$emit('addTab', {type: 'file', file: record})
          break
        }
        case '删除': {
          this.ReplaceMaterials(record,'delete')
          break
        }
      }
    },
    previewNode(item) {
      if (item.type === 'file') {
        this.$emit('addTab', {type: 'file', file: item})
      }
    }
  },
  watch: {
    materialTree(val) {
      this.inRender = true
    }
  }
}
</script>

<style scoped lang="less">
.material-manage {

  background: #fff;
  padding: 10px;
  overflow: auto;
  height: 100%;

  /deep/ .ant-table-thead > tr > th {
    text-align: center;
  }

  /deep/ .ant-table-thead > tr > th,
  /deep/ .ant-table-tbody > tr > td {
    padding: 8px 12px;
  }

  .text-yellow {
    color: orange;
  }

  .text-red {
    color: red !important;
  }

  .upload-span {
    display: inline-block;
    margin-right: 10px
  }
}
</style>
